// test.ts

import path from 'path'
import fs from 'fs'
import { MockMethod, MockConfig } from 'vite-plugin-mock'
export default [
  {
    url: '/api/get',
    method: 'get',
    response: ({ query }) => {
      return {
        code: 0,
        data: {
          name: 'vben',
        },
      }
    },
  },
  {
    url: '/api/post',
    method: 'post',
    timeout: 2000,
    response: {
      code: 0,
      data: {
        name: 'vben',
      },
    },
  },
  {
    url: '/api/text',
    method: 'get',
    rawResponse: async (_req, res) => {
      // http://localhost:5173/api/text
      const imagePath = path.join(__dirname, 'demo.png')
      fs.readFile(imagePath, (err, data) => {
        if (err) {
          res.statusCode = 500
          res.setHeader('Content-Type', 'text/plain')
          res.end('Error reading file')
        } else {
          // 设置内容类型为image/jpeg
          res.setHeader('Content-Type', 'image/png')
          // 发送图片数据
          res.statusCode = 200
          res.end(data) //将图片文件的二进制数据发送给客户端
        }
      })
    },
  },
  // mock/test.ts
  {
    url: '/api/image/:image',
    method: 'get',
    rawResponse: async (_req: any, res: any) => {
      const imageName = _req.url.replace('/api/image/', '')
      console.log('57', imageName)
      const imagePath = path.join(__dirname, 'assets', imageName)

      fs.readFile(imagePath, (err, data) => {
        if (err) {
          res.statusCode = 500
          res.setHeader('Content-Type', 'text/plain')
          res.end('Error: Unable to read image file.')
        } else {
          // 设置内容类型为 image/jpeg（或其他适当的类型）
          res.setHeader('Content-Type', 'image/jpeg')
          res.statusCode = 200
          res.end(data) // 将图片文件的二进制数据发送给客户端
        }
      })
    },
  },
  {
    url: '/api/assets/:image',
    method: 'get',
    rawResponse: async (_req: any, res: any) => {
      const imageName = _req.url.replace('/api/assets/', '')
      //http://localhost:5173/api/assets/5fc063c709c41a8f05400304.jpg 在浏览器里面可以放问到图片
      const imagePath = path.join(__dirname, 'downloads', imageName)

      fs.readFile(imagePath, (err, data) => {
        if (err) {
          res.statusCode = 500
          res.setHeader('Content-Type', 'text/plain')
          res.end('Error: Unable to read image file.')
        } else {
          // 设置内容类型为 image/jpeg（或其他适当的类型）
          res.setHeader('Content-Type', 'image/jpeg')
          res.statusCode = 200
          res.end(data) // 将图片文件的二进制数据发送给客户端
        }
      })
    },
  },
] as MockMethod[]
